package com.poobo.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.poobo.Interceptor.ActionInterceptor;
import com.poobo.aop.SystemCtrLo4jAop;
import com.poobo.entity.TbConfigList;
import com.poobo.entity.TbEqGamesInfo;
import com.poobo.entity.TbEquipment;
import com.poobo.entity.TbEquipmentConfiglist;
import com.poobo.entity.TbResources;
import com.poobo.entity.TbResourcesConfig;
import com.poobo.service.IConfigListService;
import com.poobo.service.IEqGamesInfoService;
import com.poobo.service.IEquipmentConfigListService;
import com.poobo.service.IEquipmentService;
import com.poobo.service.IResourcesService;
import com.poobo.service.IResourcesConfigService;// add by hxh 20160517
import com.poobo.util.pager.Page;
import com.poobo.util.property.PropertyUtil;
import com.poobo.util.str.StrUtil;

@Controller
@RequestMapping("equipment")
public class EquipmentCtr {
	
	@Autowired
	private IEquipmentService equipmentService;
	@Autowired
	private IEquipmentConfigListService equipmentConfigListService;
	@Autowired
	private IEqGamesInfoService eqGamesInfoService;
	@Autowired
	private IConfigListService configListService;
	@Autowired
	private IResourcesService resourcesService;
	
	// add by hxh 20160517
	@Autowired
	private IResourcesConfigService resourcesConfigService;
	
	/**
	 * 设备列表
	 * @param equipment
	 * @param page
	 * @return JSP URL
	 */
	@RequestMapping("toEquipmentList")
	public String equipmentList( TbEquipment equipment, Page page, HttpServletRequest request ){
		if( equipment.getNumber() != null ){
			request.setAttribute("number", equipment.getNumber());
		}if( equipment.getShopId() != null ){
			request.setAttribute("shopId", equipment.getShopId());
		}if( equipment.getStatus()!=null ){
			if( equipment.getStatus() == 1 ){
				request.setAttribute("status", "运行状态");
			}else if( equipment.getStatus() == 0 ){
				request.setAttribute("status", "备用状态");
			}else{
				request.setAttribute("status", "");
			}
		}
		page = equipmentService.equipmentList(equipment, page);
		request.setAttribute("pageSize", page.getPageSize());
		request.setAttribute("rowCount", page.getRowCount());
		request.setAttribute("pageNo", page.getPageNo());
		request.setAttribute("pageNum", page.getPageNum());
		request.setAttribute("equipments", page.getPageList());
		return "equipment/equipment_list";
	}
	
	/**
	 * 根据Id删除设备
	 * @param request
	 * @return
	 */
	@RequestMapping("deleteById")
	@SystemCtrLo4jAop(description="删除单个设备")
	public String deleteEquipmentById( HttpServletRequest request ){
		Integer id = Integer.parseInt(request.getParameter("equipmentId"));
		equipmentService.deleteEquipmentById(id);
		//同时删除关联表的设备配置
		eqGamesInfoService.deleteEqGamesInfoByEquipmentId(id);
		equipmentConfigListService.deleteEquipmentConfigByEquipmentId(id);
		return "redirect:/equipment/toEquipmentList.html";
	}
	@RequestMapping("deleteByIds")
	@SystemCtrLo4jAop(description="批量删除设备")
	public String deleteEquipmentByIds( HttpServletRequest request ){
		String ids = request.getParameter("ids");
		String[] idss = ids.split(",");
		Integer id = null;
		for (String idStr : idss) {
			id = Integer.parseInt(idStr);
			equipmentService.deleteEquipmentById(id);
			eqGamesInfoService.deleteEqGamesInfoByEquipmentId(id);
			equipmentConfigListService.deleteEquipmentConfigByEquipmentId(id);
		}
		return "redirect:/equipment/toEquipmentList.html";
	}
	/**
	 * 跳转编辑设备页面
	 * @param request
	 * @param equipment
	 * @return
	 */
	@RequestMapping("toEditEquipmentPage")
	public String toEditEquipment( HttpServletRequest request , TbEquipment equipment ){
		Integer id = Integer.parseInt(request.getParameter("equipmentId"));
		equipment = equipmentService.queryEquipmentById(id);
		request.setAttribute("equipment", equipment);
		return "equipment/edit_equipment";
	}
	/**
	 * 提交设备编辑数据
	 * @param equipment
	 * @return
	 */
	@RequestMapping("submitEdit")
	@SystemCtrLo4jAop(description="编辑设备")
	public String submitEdit( TbEquipment equipment ){
		equipmentService.saveEquipment(equipment);
		return "redirect:/equipment/toEquipmentList.html";
	}
	/**
	 * 导入Excel到数据库
	 * @param file
	 * @return
	 */
	@RequestMapping("importEquipmentExcel")
	@SystemCtrLo4jAop(description="Excel导入设备")
	public String importEquipmentExcel( @RequestParam(value="file",required=false) MultipartFile file ){
		try {
			File res = new File(PropertyUtil.configProperty.getProperty("resource_disk_base_path") );
			// 如果文件夹不存在则创建 
			if (!res.exists()) {
				res.mkdirs();
			}
			File saveUrl = new File(PropertyUtil.configProperty.getProperty("resource_disk_base_path") + File.separator + PropertyUtil.configProperty.getProperty("resource_equipment"));
			// 如果文件夹不存在则创建 
			if (!saveUrl.exists()) {
				saveUrl.mkdirs();
			}
			File oldFile = new File(saveUrl + File.separator + file.getOriginalFilename());
			if (oldFile.exists()) {
				oldFile.delete();
			}
			file.transferTo( new File(saveUrl + File.separator + file.getOriginalFilename()));
			System.out.println(saveUrl.getPath() + File.separator + file.getOriginalFilename());
			equipmentService.saveEquipmentExcel( new File(saveUrl.getPath() + File.separator + file.getOriginalFilename() ) );
			File newFile = new File(saveUrl + File.separator + file.getOriginalFilename());
			newFile.delete();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "redirect:/equipment/toEquipmentList.html";
	}
	
	/**
	 * 接口
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value="/findByEquipmentNumber",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String findByEquipmentNumber( HttpServletRequest request ) throws UnsupportedEncodingException{
		String number = request.getParameter("DEVEICEID");
		TbEquipment equipment = equipmentService.queryEquipmentByNumber(number);
		TbEqGamesInfo eqGamesInfo = null;
		TbEquipmentConfiglist equipmentConfiglist = null;
		TbConfigList configList = null;
		TbResources resources = null;
		Integer eid = null;
		StringBuffer sbBuffer = new StringBuffer();
		
/*		System.out.println("=====findByEquipmentNumber====="); 
		System.out.println("number = " + number);
		System.out.println("equipment = " + equipment);*/
		
		if( equipment != null ){
			eid = equipment.getId();
/*			System.out.println("eid = " + eid);*/
			eqGamesInfo = eqGamesInfoService.queryEqGamesInfoByEquipmentId(eid);
			equipmentConfiglist = equipmentConfigListService.queryEquipmentConfigByEqId(eid);			
			if( eqGamesInfo != null ){
				resources = resourcesService.queryResourcesById(eqGamesInfo.getReid());
/*				System.out.println("Reid = " + eqGamesInfo.getReid());
				System.out.println("资源名称 = " + resources.getName());
				System.out.println("服务器资源名称 = " + resources.getPath());
				System.out.println("游戏版本号= " + resources.getVersion());*/
			}
			if( equipmentConfiglist != null ){				
				configList = configListService.queryConfigListById(equipmentConfiglist.getConfigListId());
/*				System.out.println("配置列表id = " + equipmentConfiglist.getConfigListId());
				System.out.println("配置列表名称 = " + configList.getName());*/
			}
			if( resources != null ){
				sbBuffer.append(resources.getName()+","+resources.getPath()+","+resources.getVersion()+"," );
			}else{
				sbBuffer.append(null+","+null+","+null+",");
			}
			if( configList != null ){
				sbBuffer.append(configList.getListUrl());
			}else{
				sbBuffer.append(null+"");
			}
		}else{			
			sbBuffer.append("unable");
		}
		return sbBuffer.toString();
	}
	
	
	/**
	 * 接口
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value="/findEquipStateByEquipmentNumber",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String findEquipStateByEquipmentNumber( HttpServletRequest request ) throws UnsupportedEncodingException{
		String number = request.getParameter("DEVEICEID");
		TbEquipment equipment = equipmentService.queryEquipmentByNumber(number);
		TbEqGamesInfo eqGamesInfo = null;
		TbEquipmentConfiglist equipmentConfiglist = null;
		TbConfigList configList = null;
		TbResources resources = null;
		Integer eid = null;
		StringBuffer sbBuffer = new StringBuffer();
		
/*		System.out.println("=====findByEquipmentNumber====="); 
		System.out.println("number = " + number);
		System.out.println("equipment = " + equipment);*/
		
		if( equipment != null ){
			eid = equipment.getId();
/*			System.out.println("eid = " + eid);*/
			eqGamesInfo = eqGamesInfoService.queryEqGamesInfoByEquipmentId(eid);
			equipmentConfiglist = equipmentConfigListService.queryEquipmentConfigByEqId(eid);			
			if( eqGamesInfo != null ){
				resources = resourcesService.queryResourcesById(eqGamesInfo.getReid());
/*				System.out.println("Reid = " + eqGamesInfo.getReid());
				System.out.println("资源名称 = " + resources.getName());
				System.out.println("服务器资源名称 = " + resources.getPath());
				System.out.println("游戏版本号= " + resources.getVersion());*/
			}
			if( equipmentConfiglist != null ){				
				configList = configListService.queryConfigListById(equipmentConfiglist.getConfigListId());
/*				System.out.println("配置列表id = " + equipmentConfiglist.getConfigListId());
				System.out.println("配置列表名称 = " + configList.getName());*/
							
				String path = PropertyUtil.configProperty.getProperty("resource_disk_base_path") + File.separator + PropertyUtil.configProperty.getProperty("resource_ConfigListTxt");
				String filename=path + File.separator + equipmentConfiglist.getConfigListId() + ".xml";	
							
				File file = new File(filename);
				if (!file.exists()) {
				    //ActionInterceptor.generateXml(filename);
					String flag=generateXml(equipmentConfiglist.getConfigListId());
				}
				
				
			}
			if( resources != null ){
				sbBuffer.append(equipment.getStatus()+","+eqGamesInfo.getIsUpdate()+","+resources.getName()+","+resources.getPath()+","+resources.getVersion()+"," );
			}else{
				sbBuffer.append(null+","+null+","+null+","+null+","+null+",");
			}
			if( configList != null ){
				String filename=configList.getListUrl();
				filename=StrUtil.replaceAll(filename, ".txt", ".xml");
				sbBuffer.append(filename);
			}else{
				sbBuffer.append(null+"");
			}
		}else{			
			sbBuffer.append("unable");
		}
		return sbBuffer.toString();
	}
	
	// add by hxh 20160517
	public String generateXml(Integer configListId){
		String flag = null;
		TbConfigList configList = configListService.queryConfigListById(configListId);
		List<TbResourcesConfig> resourcesConfigs = resourcesConfigService.queryResourcesConfigByConfigListId(configListId);
		
	       // 建立document对象 
	       Document document = DocumentHelper.createDocument();

	       // 创建根节点
	       Element root = DocumentHelper.createElement("AllConfigureRecord");
	       document.setRootElement(root);
	       
	       //Element root = document.addElement("AllConfigureRecord");
	       // 加入一行注释 
	       //root.addComment("This is a test for dom4j, holen, 2004.9.11");
	       
	       // 加入属性内容
	       /*root.addAttribute("Id","92");
	       root.addAttribute("name","出厂配置（驯龙广告片）");
	       root.addAttribute("isEnable","1");*/
	       root.addAttribute("Id",String.valueOf(configList.getId()));
	       root.addAttribute("name",configList.getName());
	       root.addAttribute("isEnable",String.valueOf(configList.getIsEnable()));
	       
		   //第一行为列表的资源数量
		   int iReCount=resourcesConfigs.size();
		   root.addAttribute("iReCount",String.valueOf(iReCount));
		   
	       for(int i=0;i<iReCount;i++){
		       // 加入第i个节点 
		       Element node = root.addElement("ConfigureRecord");
				Short type = 0;
				String resourcesURL = null;
				String version = null;
				String resourcesName = null;
				Integer reid = resourcesConfigs.get(i).getResourcesId();//资源ID
				if( reid != null ){					
					type = resourcesService.queryResourcesById(resourcesConfigs.get(i).getResourcesId()).getType();//资源类型
					resourcesURL = resourcesService.queryResourcesById(resourcesConfigs.get(i).getResourcesId()).getPath();
					version = resourcesService.queryResourcesById(resourcesConfigs.get(i).getResourcesId()).getVersion();
					if( type==0 ){					
						resourcesName = resourcesService.queryResourcesById(resourcesConfigs.get(i).getResourcesId()).getName();
					}else{
						resourcesName = null;
					}
					if( StrUtil.isNull(version) ){
						version = null;
					}
				}
				
				Short order = resourcesConfigs.get(i).getDisplayOrder();
				Timestamp begin = resourcesConfigs.get(i).getActionDate();//开始时间
				Timestamp end = resourcesConfigs.get(i).getEndDate();//结束时间
				Integer week = resourcesConfigs.get(i).getWeek();
				Integer seconds = resourcesConfigs.get(i).getSeconds();
				//隐藏Timestamp的毫秒，转化为String类型
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
				String beginStr = df.format(begin);  
				String endStr = df.format(end);
				
		       // 加入属性内容
		       node.addAttribute("resourceId",String.valueOf(reid));
		       node.addAttribute("resourceType",String.valueOf(type));
		       node.addAttribute("appName",String.valueOf(resourcesName));
		       node.addAttribute("URL",String.valueOf(resourcesURL));
		       node.addAttribute("version",String.valueOf(version));
		       node.addAttribute("startTime",beginStr);
		       node.addAttribute("stopTime",endStr);
		       node.addAttribute("orderNumber",String.valueOf(order));
		       node.addAttribute("weekday",String.valueOf(week));
		       node.addAttribute("showTime",String.valueOf(seconds));
	       }

		try {
			String path = PropertyUtil.configProperty.getProperty("resource_disk_base_path") + File.separator + PropertyUtil.configProperty.getProperty("resource_ConfigListTxt");
			File dir = new File(path);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			String filename=path + File.separator + configListId + ".xml";
			File file = new File(filename);
			if (!file.exists()) {
				file.createNewFile();
			}else{
				file.delete();
			}
			// 将document中的内容写入文件中
			OutputFormat format = OutputFormat.createPrettyPrint();
			format.setEncoding("UTF-8");
			XMLWriter writer = new XMLWriter(new FileOutputStream(filename),format);
			writer.write(document);
			writer.close();
			flag = "succ";
		} catch (IOException e) {
			flag = "fail";
			e.printStackTrace();
		}
		return flag;
	}
		
}
